package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.IApCommentService;
import com.heima.comment.vo.ApCommentVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApCommentServiceImpl implements IApCommentService {

    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        // 当前登录人
        User user = UserThreadLocalUtil.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApComment apComment = new ApComment();
//        apComment.setId();// mongo可以自动赋值
        if (user.getUserId()==0){  // 以游客身份评论
            apComment.setUserId(user.getUserId());
            apComment.setUserName("游客");
            apComment.setImage(null);
        }else {
            ResponseResult<ApUser> responseResult = userFeign.getById(user.getUserId());
            ApUser apUser = responseResult.getData();
            apComment.setUserId(user.getUserId());
            apComment.setUserName(apUser.getName());
            apComment.setImage(apUser.getImage());
        }
        apComment.setArticleId(dto.getArticleId());
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setRepay(0);
        apComment.setCreatedTime(new Date());
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();

    }

    @Override
    public ResponseResult loadComment(CommentDto dto) {
        // 当前登录人
        User user = UserThreadLocalUtil.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 1.根据文章id查询评论列表
        // 2.按照评论时间排列
        // 3.分页时的条件是  评论时间<minTime
        // 分页判断数据小于前端传递的最小时间
        // 每页默认显示10条评论数据
        Query query = new Query(Criteria.where("articleId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        // 分页 和 排序
        query.limit(dto.getSize());
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);

        List<ApCommentVo> commentVoList = new ArrayList<>();
        for (ApComment apComment : commentList) {
            ApCommentVo apCommentVo = new ApCommentVo();
            BeanUtils.copyProperties(apComment,apCommentVo);
            // 都需要从APCommentLike表中查询当前登录人对这个评论是否点赞
            // TODO 当前登录人是否对这个评论点赞   完了做
//            redisTemplate.boundValueOps("comment_like_"+user.getUserId()+"_"+dto.getCommentId()).set("");
            if (redisTemplate.hasKey("comment_like_"+user.getUserId()+"_"+apComment.getId())) {
                apCommentVo.setOperation(0);  // 0:当前登录人已点赞   1：未点赞
            }else {
                apCommentVo.setOperation(1);  // 0:当前登录人已点赞   1：未点赞
            }
            commentVoList.add(apCommentVo);
        }

        return ResponseResult.okResult(commentVoList);
    }

    @Override
    public ResponseResult commentLike(CommentLikeDto dto) {
        // 判断登录人
        User user = UserThreadLocalUtil.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 保存点赞或取消点赞记录
        if (dto.getOperation() == 0){
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setUserId(user.getUserId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation(dto.getOperation()); //0 点赞  1 取消点赞
            mongoTemplate.save(apCommentLike);

            // 更新评论表的点赞数量+1或者-1
            // sql语句：update ap_comment set likes = likes-1 where id =??
            Query query = new Query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",1);
            mongoTemplate.updateFirst(query,update,ApComment.class);

            //记录到Redis中：记录当前登录人是否对这个评论点赞
            // key要体现出谁对哪个评论点赞
            redisTemplate.boundValueOps("comment_like_"+user.getUserId()+"_"+dto.getCommentId()).set("");
        }else {
            // 取消点赞
            // 把当前用户点赞的数据删除 delete from ap_comment_like where userId=?? and comment_id=??
            mongoTemplate.remove(new Query(Criteria.where("userId").is(user.getUserId()).and("commentId").is(dto.getCommentId())),ApCommentLike.class);

            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setUserId(user.getUserId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation(dto.getOperation()); //0 点赞  1 取消点赞
            mongoTemplate.save(apCommentLike);

            Query query = new Query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",-1);
            mongoTemplate.updateFirst(query,update,ApComment.class);
            // 取消点赞，删除Redis中的标记
            redisTemplate.delete("comment_like_"+user.getUserId()+"_"+dto.getCommentId());

        }
        return ResponseResult.okResult();
    }
}
